<?php
class processActionForm extends BaseForm
{
	
  public $obligatoires = array();	
  public $hiddenFields = array();
  public $arrayFields = array();			

  public function configure()
  {
  	$i18N = sfContext::getInstance()->getI18N();
  	
  	$this->setWidgets(array('commentaire' =>  new sfWidgetFormTextareaTinyMCE(array('height'=>'250')),
  						'hideConfirmation' => new sfWidgetFormInputCheckbox(),
  						'acteur' =>  new sfWidgetFormInputHidden(),
  						'acteurclass' =>  new sfWidgetFormInputHidden(),
  						'action_id' =>  new sfWidgetFormInputHidden(),
  						/*'clotureTechnique' =>  new sfWidgetFormInputHidden(),
  						'cloture' =>  new sfWidgetFormInputHidden(),
  						'debutTraitement' =>  new sfWidgetFormInputHidden(),
  						'finTraitement' =>  new sfWidgetFormInputHidden(),*/
  						'prestataire' => new sfWidgetFormInputCheckbox(),
  						'prestatairenom' => new sfWidgetFormInputText(),
  						'justif_prestataire' => new sfWidgetFormTextarea(),
  				)
  	);
	$this->offsetGet('prestatairenom')->getWidget()->setAttributes(array(
			'class'=> "form text",
			'tmt:errorclass'=> "error",
			'tmt:message'=> "Champ obligatoire",
			));
  	
  	$this->offsetGet('prestataire')->getWidget()->setAttributes(array(
			'class'=> "radioCheck form",
  			'onchange'=> "showNomPresta()",
			
			));
  	
	$this->offsetGet('commentaire')->getWidget()->setAttributes(array(
			'class'=> "textarea form",
			));
	
	$this->hiddenFields = array();
	$this->arrayFields = array();			
	// $this->widgetSchema->setNameFormat('demandes1[%s]');
	// On active le formatage particulier
	$this->getWidgetSchema()->setFormFormatterName('app');

	$this->getWidgetSchema()->setLabels(array(
			'hideConfirmation' => $i18N->__('Don\'t show e-mail confirmation'),
			'prestataire' => utf8_encode('Dossier confié à un prestataire'),
  			'prestatairenom' => 'Prestataire',
			'prestataire_id' => 'Nom Prestataire',
  			'justif_prestataire' => 'Justification non externalisation',
		));	
		
	$this->getWidgetSchema()->setHelps(array(
		    'Valideur' =>  'Valideur',
			'hideConfirmation' => $i18N->__('Check to hide the sent e-mails confirmation'),
			'prestatairenom' => 'Ce dossier est externalisable. Merci de saisir le nom  du prestataire.',
			'justif_prestataire' => utf8_encode("Ce dossier est externalisable. Merci de nous dire pourquoi il n'a pas �t� envoy� vers un prestataire."),
		));	
	
	$utilisateur = sfContext::getInstance()->getUser()->getUserProfile();
	$value = $utilisateur->getParam('hideMailsConfirmation');
	if($value=='true'){
		$value = true;
	}else{
		$value = false;
	}
	$this->setDefault('hideConfirmation',$value);
	
    $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);
  }
  
  
  public function setWidgetsFromAction($action){
  	$this->setDefault('action_id', $action->id);
  	/*
  	if($action->ferme){
      	$this->setDefault('cloture','true');
    }else{
    	$this->setDefault('cloture','false');
    }
    if($action->fermetechnique){
    	$this->setDefault('clotureTechnique','true');		 
    }else{
    	$this->setDefault('clotureTechnique','false');
    }
    if($action->debuttraitement){
    	$this->setDefault('debutTraitement','true');
    }else{
    	$this->setDefault('debutTraitement','false');
    }
	if($action->fintraitement){
    	$this->setDefault('finTraitement','true');
    }else{
    	$this->setDefault('finTraitement','false');
    }
    */
    $this->setDefault('commentaire',$action->messageclient);
  }  

  public function setActeurs($acteurs, $titre ){
  	$i18N = sfContext::getInstance()->getI18N();
  	$choices = array(''=>$i18N->__('Please select a value...'));
  	foreach($acteurs as $opt){
		$choices[$opt['id']]=$opt['description'];
	}
  	$this->widgetSchema['acteur'] =new sfWidgetFormChoice(array('multiple' => false,
							  'expanded' => false,
							  'choices'  => $choices));
  	
	$this->getWidget('acteur')->setAttributes(array(
			'class'=> "form combobox required",
	    	'tmt:invalidindex'=> "0",
			'tmt:errorclass'=> "error",
			'tmt:message'=> "Champ obligatoire",
			));
	$this->getWidgetSchema()->setHelp('acteur', '');
	$this->getWidget('acteur')->setLabel($titre);

  }
  
  public function setValideurPersonne($valideur, $titre ){
  	$q = Doctrine::getTable('lienvalideurpersonne')
	 		->createQuery('a')
	 		->select('a.id, b.name')
	 		->innerJoin('a.personnes b')
	 		->addWhere('a.valideur_id = ? ', $valideur->id);
	$records = $q->execute(); 		
	$valideurs = array(''=>'Veuillez s&eacute;lectionner une valeur...');
	foreach($records as $item){
		$valideurs[$item->id] = $item->personnes->name;
	}
  	$this->widgetSchema['valideurPersonne'] =new sfWidgetFormChoice(array('multiple' => false,
							  'expanded' => false,
							  'choices'  => $valideurs));
	$this->offsetGet('valideurPersonne')->getWidget()->setAttributes(array(
			'class'=> "form required combobox",
	    	'tmt:invalidindex'=> "0",
			'tmt:errorclass'=> "error",
			'tmt:message'=> "Champ obligatoire",
			));
  	
  	$labels=$this->getWidgetSchema()->setHelp('valideurPersonne', ' ');
  	$labels=$this->getWidgetSchema()->setLabel('valideurPersonne', $titre);
  }  

  
	public function setCommentaireObligatoire()
	{
		$this->offsetGet('commentaire')->getWidget()->setAttributes(array(
				'class'=> "textarea form required",
		    	'tmt:required'=> "true",
				'tmt:errorclass'=> "error",
				'tmt:message'=> "Champ obligatoire",
			    //'onchange'=> "validatedates()",
				));
	  	$this->getWidget('commentaire')->setLabel('Commentaire *');
		$this->getWidgetSchema()->setHelp('commentaire', 'Veuillez saisir un commentaire');
	  	
	}
  
  /*
   * Cr�ation d'un widget pour permetre a l'utilisateur de indiquer si suite a son action, il faut cr�er un autre dossier li�e a celui qui est en train de valideur.
   * 
   * @param string $label   l'etiquette du widget.
   * 
   * */
  
  public function setDossierAutomatique($label){
  	$funcs = new erdfFuncs();
  	$options = $funcs->getArrayActions(true, array('OUI','NON'));
  	$nom = 'creationDossier';
  	$this->widgetSchema[$nom] = new sfWidgetFormChoice(
													array('multiple' => false,
									  					  'expanded' => false,
									  					  'choices'  => $options,));
  	$helps=$this->widgetSchema->getHelps();
  	$helps['creationDossier']=' ';
  	$this->widgetSchema->setHelps($helps);
	$this->offsetGet($nom)->getWidget()->setAttributes(array(
					'class'=> "combobox form required",
					'tmt:invalidindex'=> "0",
	    			'tmt:required'=> "true",
					'tmt:errorclass'=> "error",
					'tmt:message'=> "Champ obligatoire",));
	$this->widgetSchema[$nom]->setLabel($label);
  }
  
  /* Filtre les candidates des prestataires par region et domaine de la demainde
   * 
   * @param dossier $dossier
   * 
   * return void
   * */
  public function setPrestatairesWidget($dossier)
  {
  	$q = Doctrine_Query::create()->from('prestataire p')->select('id, nom');
  	$q->addWhere('p.activestatus = 0')->addWhere('(p.region_id = ? or p.region_id is null)', $dossier->regionClient_id)->addWhere('p.domaine_id = ? ', $dossier->domaine_id);
  	$q->setHydrationMode(Doctrine::HYDRATE_ARRAY);
  	$this->getWidget('prestataire_id')->setOption('method', 'nom');
  	$this->getWidget('prestataire_id')->setOption('query', $q);
  }
  
  
  /*
   * Cr�ation d'un widget pour que l'utilisateur puisse choisir entre plusieurs d�finitions de d�rogation.
   * L'application cherche s'il existent d�finitions de d�rongation pour la cat�gorie de demande que l'utilisateur est en train de valider.
   * S'il existe un seule categorie, le widget est seule lecture avec le type de d�rogation d�ja saisi.
   * 
   * @param categoriedemande $categoriedemande    La categorie pour laquelle il faut chercher les d�finitions de d�rogation
   * @param int  $id_role						  L'id du role pour lequel il faut chercher les d�finitions de d�rogation. C'est le r�le qui peut demander la derogation.
   * 
   * */
  
  public function setDerogationsWidget($categoriedemande, $id_role){
  	$derogations_def = $categoriedemande->getDerogationsForRole($id_role);
  	$i18N = sfContext::getInstance()->getI18N();
  	if(count($derogations_def)>0){
  		$fieldName = 'derogationdef_id';
  		$options = array(''=>$i18N->__('Please select a value...'));
  		foreach($derogations_def as $def){
  			$options[$def['id']] = $def['description'];
  		}
  		$this->widgetSchema[$fieldName] =new sfWidgetFormChoice(array('multiple' => false,
							  'expanded' => false,
							  'choices'  => $options));
  		$attributes = array(
				'class'=> "combobox form required",
	    		'tmt:required'=> "true",
				'tmt:errorclass'=> "error",
				'tmt:message'=> $i18N->__("Required Attribute"),
  				'onchange'=>'showDerogationDefComment();');
  		
  		if(count($derogations_def)==1){
  			foreach($derogations_def as $def){
  				$this->setDefault($fieldName, $def['id']);
  				$attributes["disabled"] = 'true';
  			}
  		}
  		$this->offsetGet($fieldName)->getWidget()->setAttributes($attributes);
  		$this->widgetSchema[$fieldName]->setLabel($i18N->__('Derogation type'));
  		
  	}
  }
  
  /*
   * Cr�ation d'un widget Contenir le fichier signe par l'utilisateur.
   * L'application cherche s'il existent un fichier dans la categorie de la demande.
   * 
   * 
   * */
  
  public function setSignatureWidget(){
  	
  	$i18N = sfContext::getInstance()->getI18N();
  	$fieldName = 'fichier_signature';
	$dirName = 'sf_upload_dir';
	$path = sfConfig::get($dirName);
	$this->widgetSchema[$fieldName] = new sfWidgetFormInputFile();
	$this->validatorSchema[$fieldName] = new sfValidatorFile(array('required' => $notnull,
		     	'path' => $path
		));
  		
		
  	$attributes = array(
				'class'=> "combobox form required",
	    		'tmt:required'=> "true",
				'tmt:errorclass'=> "error",
				'tmt:message'=> $i18N->__("Required Attribute"));
  		
  	$this->offsetGet($fieldName)->getWidget()->setAttributes($attributes);
  	$this->widgetSchema[$fieldName]->setLabel($i18N->__('File'));
  	$max = ini_get('upload_max_filesize');
  	$helps = $this->widgetSchema->getHelps();
  		
  	$helps[$fieldName] .= $i18N->__('(Maximum file size is %max_size% bytes)',array('%max_size%'=>$max));
	$this->widgetSchema->setHelps($helps);
  	
  }
  
  /* Ajoute les champs a modifier au formulaire selon les definition de l'action
   * 
   * @param action $action | L'action qui est en train d'etre executé
   * @param sfDoctrineRecord $object  | Le dossier ou le questionnaire ou l'action s'execute. 
   * 
   * */
  
  public function addFieldsToModify(action $action, $objectBase){
  		// Update fields from the main form.
  		$i18N = sfContext::getInstance()->getI18N();
		$q = Doctrine_Query::create()->from('item_action_field a')
				->leftJoin('a.categorie cfr')
				->addSelect('a.*')
				->addSelect('cfr.owner_id')
				->addWhere('a.owner_id = ?', $action->id)
				->setHydrationMode(Doctrine::HYDRATE_ARRAY);
  		$results = $q->execute();
  		foreach($results as $item){
  			$flag = true; //Variable pour gérer des cas particulers.
  			$field = trim($item['fieldname']);
  			
  			if($flag)
  			{
				if($item['detail'] and get_class($objectBase) != 'questionnaire')
				{
					if(!isset($detail)){
						$detail = $objectBase->getDetail();
						$object = $detail;
	  				}
				}else{
					$object = $objectBase;
				}
				$formclass = get_class($object) . 'Form';
				$objDef = new objectDef(get_class($object));
				$form = new $formclass;
	  			if(isset($objDef->attributes[$field])){
	  				$fieldName = $field;
	  				if($objDef->attributes[$field]['type']=='BO')
					{
						$fieldName = $field.'_id';
					}
					$value = $object->$field ;
					if(is_object($value)){
				      	$value = $value->id;
				    }
				    if(!($item['onlyblank'] and !empty($value))) //le champ doit apparaitre seulement si la valeur est vide
				    { 
						$filter = $item['filter'];
				        //if($field=='domaineconcerne') $filter = 'reclamation = true';
					    $objDef->attributes[$field]['show']=true;
					    if(empty($value) and $item['xdefault']!='')
					    {
					    	//
					    	if($att['show'])
					    	{
					    		$dateformat='d/m/Y'; 	
					    	}
					    	else 
					    	{
					    		$dateformat='Y-m-d'; 	
					    	}
					    	$value = Util::processDefaultExpression($item['xdefault'], $att['type'], $dateformat);
					    }
						$this->setMyWidget($field, $objDef, $item , $filter, $value, null, $form);
						if(trim($item['caption'])!='') $this->getWidget($fieldName)->setLabel($item['caption']);
						if(trim($item['helptext'])!='') $this->getWidgetSchema()->setHelp($fieldName, $item['helptext']);
						if($item['readonly']) $this->getWidget($fieldName)->setAttribute('disabled', true);
						$originalAttributes =  $this->getWidget($fieldName)->getAttributes();
						if($item['notnull'])
						{
							$this->getWidget($fieldName)->setAttribute('tmt:errorclass', "invalid");
							if($objDef->attributes[$field]['type']=='BO')
							{
								$this->getWidget($fieldName)->setAttribute('tmt:invalidindex', "0");
							}
							elseif($objDef->attributes[$field]['type'] == 'enum')
							{
								$this->getWidget($fieldName)->setAttribute('tmt:invalidindex', "0");
							}				
							elseif($objDef->attributes[$field]['type'] == 'boolean')
							{
								$this->getWidget($fieldName)->setAttribute('tmt:minchecked', "1");
							}
							elseif($att['type']=='CheckboxList')
							{
								$this->getWidget($fieldName)->setAttribute('tmt:minchecked', "1");
								$this->getWidget($fieldName)->setAttribute('tmt:message', $i18N->__("You must choose at least one option"));
								
							}
							else
							{
								$this->getWidget($fieldName)->setAttribute('tmt:required', "true");
							}
						}
						$newAttributes = Util::getArrayFromStr($item['htmlattributes'], ';');
						if($item['onchangefunction']) $newAttributes['onchange'] = $item['onchangefunction'];
						$this->getWidget($fieldName)->setAttributes(array_merge($originalAttributes, $newAttributes));
						if($item['script']!='')
						{
							$newfunc = create_function('$form, $widget, $item_action_field, $objDef, $object, $detail', htmlspecialchars_decode($item['script']));
							$result = $newfunc($this, $this->getWidget($fieldName), $item, $objDef, $object, $detail);
						}
						$this->arrayFields[$field] = array('objDef'=>$objDef, 'att'=> $objDef->attributes[$detailField], 'item_action_field'=>$item);				    	
				    }

			    }
  			}
			
		}	
     }
     
     public function renderFieldsToModify(){
     	$html = '';
     	
     	foreach($this->arrayFields as $field => $item){
	      	$attDef = $item['att'];
	      	$objDef = $item['objDef'];
	      	$def = $item['item_action_field'];
	      	$attributes = Util::getArrayFromStr($def['htmlattributes'], ';');
	      	
	      	if($attDef['type']==file)
	      	{
      			
      			if($def['detail'])
      			{
	      			$obj = $demande->getDetail();
      			}
      			else
      			{
      				$obj = $demande;
      			}
	      		$namefile = $obj->$field; 
				if($namefile!=''){
					$attributes['value'] = $namefile;
				}
				$html .= $this[$field]->renderRow($attributes);
				$html .= $detailObjDef->renderFile($obj, $field, $objDef->attributes[$field], '', true);
				$html .= '<br />';
      			
      		}
      		else
      		{
      			$objDef->attributes['show']=true;
      			$html .= $objDef->renderAttributeWidget($this, $field, $hide = array(), $attributes);	
      		}	
      	}
      	return $html;
     }
     
     
	 public function setMyWidget($fieldName, objectDef $objDef, $fieldDef, $filter = '', $default, $options = null, $form = null){
		$i18N = sfContext::getInstance()->getI18N();
  		$this->widgetSchema->getFormFormatter()->setTranslationCatalogue('forms');
		$att = $objDef->attributes[$fieldName];
		Util::sendDebug('warning: ' . $att['type']);
		
		
		if($att['type']=='BO')
	   	{
			$fieldName = $fieldName.'_id';	
		}			
   		
	 	/****
		 * WIDGET CREATION DEPENDING ON DATATYPE
		 * *****************/
	 	if(($att['type']=='BO' or $att['type']=='array')){
	 		if($att['relatedClass']!=''){
					$relatedClass = $att['relatedClass'];
			}else{
					$relatedClass = $doctColDef['relatedClass'];
			}
	 		if($relatedClass!=''){	
	 			if(!is_null($options)){
	 				$this->widgetSchema[$fieldName] = new sfWidgetFormChoice(
													array('multiple' => false,
									  					  'expanded' => false,
									  					  'choices'  => $options,));
	 				
	 			}else{
	 				$relatedObjDef = new objectDef($relatedClass);
					$relatedTable = Doctrine::getTable($relatedClass);
					$id = $relatedTable->getIdentifier();	
					if($relatedObjDef){
							$descriptor = $relatedObjDef->descriptor;
				   	}else{
							$searchBar = new searchBar();
							$descArray = $searchBar->descArray; 
							$columns = $relatedTable->getFieldNames();
							foreach($columns as $key){ // => $attDef
								if(in_array($key,$descArray)){
									$descriptor = $key;	
								}
							}
							if($descriptor=='') {
								$descriptor = $id;
							}		
							unset($searchBar);
							unset($descArray);
							unset($columns);
							
					}
					//if($descriptor=='') $descriptor = $id ;
					//$filter = '';
					$addEmpty = true;
					$isnumeric = false;
					if(is_null($form)){
						$q=Doctrine_Query::create()
		    					->select('a.'.$id.' as id, a.'.$descriptor.'  as name')
							    ->from($relatedClass.' a') 
							    ->orderBy('a.'.$descriptor);
					}else{
						$q = $form->getWidget($fieldName)->getOption('query');
					}
	 				if(!$filter==''){
			 			$q->andWhere('a.'.$filter);
			 		}		
			 		
					if($relatedClass){
						$regConfMng = new regionalConfigMng($id_region);
						$q = $regConfMng->addRegionalFilterToView($q, $relatedObjDef);
					}
					
					$this->widgetSchema[$fieldName] = new sfWidgetFormDoctrineChoice(
	 								array('model' => $relatedClass,
	 								'method'=> 'get'.$descriptor,
	 								'query' => $q,
	 								'add_empty' => sfContext::getInstance()->getI18N()->__('Please select a value...')));
		 			/*
					$options = $util->getOptions($relatedClass, $id, $descriptor, $filter, $addEmpty, $isnumeric);
					$this->widgetSchema[$fieldName] = new sfWidgetFormChoice(
													array('multiple' => false,
									  					  'expanded' => false,
									  					  'choices'  => $options,));*/
				}		
	 		}		
		}elseif($att['type']=='secret'){
			 $this->widgetSchema[$fieldName] = new sfWidgetFormInputPassword();
		}elseif($att['type']=='boolean'){
			 $this->widgetSchema[$fieldName] = new sfWidgetFormInputCheckbox();
		}elseif($att['type']=='date' or $att['type']=='timestamp'){
		     $this->widgetSchema[$fieldName] = new sfWidgetFormDateJS();
		}elseif($att['type']=='image'){
		     $this->widgetSchema[$fieldName] = new sfWidgetFormInputFile();
		     $this->validatorSchema[$fieldName] = new sfValidatorFile(array('required' => $notnull,
		      'path' => sfConfig::get('sf_icons_dir'),
		      'mime_types' => 'web_images',
		     ));
		}elseif($att['type']=='file'){
		     $this->widgetSchema[$fieldName] = new sfWidgetFormInputFile();
		     $this->validatorSchema[$fieldName] = new sfValidatorFile(array('required' => $notnull,
		     	'path' => sfConfig::get('sf_upload_dir'),
		     ));
		}elseif(($att['type']=='integer' or $att['type']=='string' or $att['type']=='float') and !is_null($options)){
			$this->widgetSchema[$fieldName] = new sfWidgetFormChoice(
											array('multiple' => false,
							  					  'expanded' => false,
							  					  'choices'  => $options,));			
		}elseif($att['type']=='array'){
			if($att['relatedClass']!=''){
						$relatedClass = $att['relatedClass'];
			}else{	
						$relatedClass = $doctColDef['relatedClass'];
			}
		 	if($relatedClass!=''){	
		 			if(is_null($options)){
		 				$relatedObjDef = new objectDef($relatedClass);
						$relatedTable = Doctrine::getTable($relatedClass);
						$id = $relatedTable->getIdentifier();	
						if($relatedObjDef->classExists){
								//$descriptor = ''; 
								$descriptor = $relatedObjDef->descriptor;
						}
						if($descriptor=='') $descriptor = 'id' ;
						//$filter = '';
						$addEmpty = true;
						$isnumeric = false;
						$options = array();
						
						$options = Util::getOptions($relatedClass, $id, $descriptor, $filter, $addEmpty, $isnumeric);
						$this->widgetSchema[$fieldName] = new sfWidgetFormChoice(
															array('multiple' => false,
											  					  'expanded' => false,
											  					  'choices'  => $options,));
				}
				if(isset($options[0])){
					$options[0] = $i18N->__('You can select multiple choices (Ctrl + clic)');
				}
				if(isset($options[''])){
					$options[''] = $i18N->__('You can select multiple choices (Ctrl + clic)');
				}
				
		 	}elseif($att['enumValues']!=''){
		 		$options = Util::getArrayFromStr(Util::stripAccents2($att['enumValues']),';',$i18N->__('You can select multiple choices (Ctrl + clic)'),'=>');
		 	}
			$this->widgetSchema[$fieldName] = new sfWidgetFormChoice(
			array('choices'=>$options, 'multiple' => true,'expanded' => false));				
		}elseif($att['type'] == 'enum'){
			if(!isset($options)){
				$options = Util::getArrayFromStr(Util::stripAccents2($att['enumValues']),';',true,'=>');
			}
			$this->widgetSchema[$fieldName] = new sfWidgetFormChoice(
			array('choices'=>$options, 'multiple' => false,'expanded' => false));
		}else{
			$this->widgetSchema[$fieldName] = new sfWidgetFormInputText();/*Widget par default!*/
 		}
		
 		$notnull = false;
		if($att['notnull'] or $fieldDef['notnull']){
		 	$notnull = true;
		}
 		
 		/****
		 * LABELS
		 * *****************/
		
		if($att['label']==''){
			$label = $fieldName;
		}else{
			$label = $att['label'];
		}
		if($notnull){
		 	 $label .= ' *';
		}
		
		$this->offsetGet($fieldName)->getWidget()->setLabel($label);
		unset($label);
		
		/****
		 * HELPS
		 * *****************/
		
		$helps = $this->widgetSchema->getHelps();
		
		if($fieldDef['helttext']!=''){
			$help = $fieldDef->helttext ;
		}else{
		 	if($att['help']==''){$help = ' ';}else{ $help = $att['help'];};
		}
		if($att['type']=='file')
  		{   
  			$max = ini_get('upload_max_filesize');
			$help .= $i18N->__('(la taille maximale du ficher est '.$max.'o )');
		}			
		$this->getWidgetSchema()->setHelp($fieldName, $help);
		
		
		/****
		 * HTML ATTRIBUTES
		 * (Including tmt validator !)
		 * *****************/
		$concatError = '';
		$attributes['tmt:message'] = ''; 
		if($att['show'] and $att['type']!= 'List')
		{
			$attributes=array('class' => 'text');
			
			if(($att['type']=='BO'or$typeDoct=='BO') and $fieldName<>'id' and $att['type']!='array')
			{
				$attributes['class'] = 'combobox';
			}
			elseif(($att['type']=='integer' or $att['type']=='string' or $att['type']=='float') and !is_null($options))
			{
				$attributes['class'] = 'combobox';		
			}
			elseif($att['type']=='integer')
			{
				$attributes['tmt:pattern'] = "integer";
				$attributes['tmt:message'] = $concatError . $i18N->__("Incorrect Integer");
				$concatError = ' / ';
			}
			elseif($att['type']=='float')
			{
				$attributes['tmt:pattern'] = "number";
				$attributes['tmt:message'] .= $concatError . $i18N->__("Incorrect Float");
				$concatError = ' / ';
			}
			elseif($att['type']=='date' or $att['type']=='timestamp')
			{
				$attributes['class'] = 'date';
				$attributes['tmt:datepattern'] = "DD/MM/YYYY";
				if(!isset($attributes['tmt:message']))
					$attributes['tmt:message'] = '';
				$attributes['tmt:message'] .= $concatError .  $i18N->__("Incorrect date format"); //Formato de fecha incorrecto "Le format de la date est incorrecte";
				$concatError = ' / ';
			}
			elseif($att['type']=='blob')
			{
				$attributes['class'] = 'textarea';
			}
			elseif($att['type']=='boolean')
			{
				$attributes['class'] = 'radioCheck';
			}
			elseif($att['type']=='array')
			{
				$attributes['class'] = 'array';
				if(isset($options[0])){
					$attributes['tmt:invalidindex'] = "0";
				}
				if(isset($options[''])){
					$attributes['tmt:invalidindex'] = '';
				}
			}
			
			if($notnull)
			{	
				$attributes['class'] = $attributes['class'].' required';
				$attributes['tmt:errorclass']=  "invalid";
				if(!isset($attributes['tmt:message']))
					$attributes['tmt:message'] = '';
					
				$attributes['tmt:message'] .= $i18N->__("Required Attribute"); //"Atributo Obligatorio"; "Champ obligatoire";
				$concatError = ' / ';			
				if($att['type']=='BO' or $typeDoct=='BO')
				{
					$attributes['tmt:invalidindex'] = "0";
				}else
				{
					$attributes['tmt:required'] = "true";
				}
				if(($att['type']=='integer' or $att['type']=='string' or $att['type']=='float') and !is_null($options))
				{
					$attributes['tmt:invalidindex'] = "0";
				}
			}
			if($fieldDef['readonly'])
			{
				if($att['type']=='date' or $att['type']=='timestamp'){
				     $this->widgetSchema[$fieldName] = new sfWidgetFormInputText();
				}
			 	$attributes['disabled'] = 'true';
			 }
			 if($att['size']!="0" and $att['size']!=''){
			 	$attributes['maxlength'] = $att['size'];
			 }
			 $attributes['class'] = $attributes['class'].' form';
			 if( $att['ajaxFunction']!='') $attributes['onChange'] = $att['ajaxFunction'];
			 if($att['pattern']!=''){
			 	$attributes["tmt:pattern"] = $att['pattern'] ;
			 }
		 
			 if($att['errorMessage']!=''){
			 	$attributes['tmt:message'] .= $concatError.$att['errorMessage'];
			 	$concatError = ' / ';
			 }			 
			 if(isset($attributes['tmt:message'])){
			 	if($attributes['tmt:message']=='') unset($attributes['tmt:message']);
			 }
			 $this->offsetGet($fieldName)->getWidget()->setAttributes($attributes);
		 }else{
		 	if($fieldName=='id'){
		 		if(sfConfig::get('app_general_idAreGuids', false)){
		 			$this->widgetSchema[$fieldName] = new sfWidgetFormInputHidden();
		 		}	
		 	}else{
		 		$this->widgetSchema[$fieldName] = new sfWidgetFormInputHidden();
		 	}
		 	
		 	//unset($form[$fieldName]);
		}
		
		if(is_null($default)){
			if($att['type']=='boolean'){
				if($fieldDef['default']==''){
					$defaultValue = $fieldDef['default']; 
				}else{
					$defaultValue = $att['default'];
				}
				if($defaultValue=='true' or $defaultValue==1){
					$this->setDefault($fieldName, true);
				}else{
					$this->setDefault($fieldName, false);
				}
			}else{
				if($defaultValue!=''){
					if($defaultValue=='currentDate'){
					 	if($att['show']){
					 		$this->setDefault($fieldName, date("d/m/Y"));
					 	}else{
					 		$this->setDefault($fieldName, date("Y-m-d"));
					 	}
					}elseif($defaultValue=='currentHour'){
						 	$this->setDefault($fieldName, date("H:i"));		
				 	 }elseif($defaultValue=='linkedUser'){
				 	 		$user = sfContext::getInstance()->getUser()->getUserProfile();
							$this->setDefault($fieldName, $user->id);
					 }else{
					 	$this->setDefault($fieldName, $defaultValue);
					 }			
				}
			}
		}else{
			if($att['type']=='date' or $att['type']=='timestamp'){
				$dateArray=explode('/',$default);
				if(count($dateArray)==3){
					$xdate = mktime(0,0,0,$dateArray[1],$dateArray[0],$dateArray[2]);
				}else{
					$dateArray=explode('-',$default);
					$xdate = mktime(0,0,0,$dateArray[1],$dateArray[2],$dateArray[0]);
					unset($dateArray);
				}
				if($att['readOnly']){
					$format = "Y-m-d";
				}else{
					$format = "d/m/Y";
				}	
				$this->setDefault($fieldName, date($format,$xdate));
			}else{
			 	$this->setDefault($fieldName, $default);
			} 
		}
		unset($options);
		unset($attributes);
		unset($att);
		unset($objectDef);
		unset($util);
		unset($obj);
  		unset($objTable);
		unset($class);  	
		unset($doctColDef);
		unset($util);
		unset($doctrineColumns);
		unset($attributes);
	 }	
	 
}